<template>
  <div class="batch-add-service">
    <div class='batch-add-service__box'>
      <div v-show="list.length ===0">无待添加服务号，请重新登录或去用户中心检查是否新加服务号</div>
      <div v-show="list.length !==0">
        <el-form :model="form" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm" label-position="top">
          <div class="margin-t-15">
            <span>服务号类型：</span>
            <el-radio-group v-model="form.type">
              <el-radio label="normal">普通</el-radio>
              <el-radio label="lightweight">轻量级</el-radio>
            </el-radio-group>
          </div>
          <div class="">
              <div v-for="(item, i) in list" class="margin-t-15" :key="list[i]._id">
                <el-checkbox v-model="list[i].isChecked">服务号&nbsp;&nbsp;{{list[i]._id}}</el-checkbox>
                <div class="margin-t-7">转给技能组／座席</div>
                <div class="margin-t-7">
                  <div style="width: 90px;float: left;margin-right: 10px">
                    <el-select v-model="list[i].type" placeholder="请选择" style="width: 90px">
                      <el-option label="技能组" value="queue"></el-option>
                      <el-option label="座席" value="agent"></el-option>
                    </el-select>
                  </div>
                  <div>
                    <el-select
                      v-if="list[i].type === 'agent'"
                      size="mini"
                      v-model="list[i].agent"
                      collapse-tags
                      :placeholder="$t('public.pleasePick')" filterable>
                      <el-option
                        v-for="(item, index) in allAgent"
                        :label="item.displayName + '['+ item.exten + ']'"
                        :key="item._id"
                        :value="item._id">
                      </el-option>
                    </el-select>
                    <el-select size="mini"
                                v-if="list[i].type === 'queue'"
                                v-model.trim="list[i].peerId"
                                :placeholder="$t('report.queueNaSea')"
                                filterable>
                      <el-option v-for="item in mailQueues"
                                  :label="item.DisplayName"
                                  :value="item.Exten"
                                  :key="item._id"></el-option></el-select>
                  </div>
                </div>
              </div>
          </div>
        </el-form>
      </div>
    </div>
    <div class="batch-add-service__footer">
      <slot name="footer">
        <el-button class = 'batch-add-service__button' @click='cancelClick'>
          取消
        </el-button>
        <el-button class = 'batch-add-service__button' type="primary" @click='saveClick'>
          保存
        </el-button>
      </slot>
    </div>
  </div>
</template>
<script>
  // import {deepClone} from '@/utils/m7Utils'
  export default {
    name: 'batchAddService',
    data () {
      return {
        list: [],
        form: {
          type: 'normal'
        },
        rules: {
          type: { required: true, message: '请选择服务类型', trigger: 'change' }
        }
      }
    },
    props: {
      availableService: Array
    },
    components: {
    },
    watch: {
      availableService () {
        this.getAvaliableService()
      }
    },
    computed: {
      allAgent () {
        if (this.$store.state.session.ivrMap && this.$store.state.session.ivrMap[this.pbx]) {
          let that = this
          let _account = this.$store.state.session.ivrMap[this.pbx].data.account_user
          return (_account || []).filter((item) => {
            return that.pbx === item.pbx && item.status === 'enable'
          })
        } else {
          return []
        }
      },
      mailQueues () {
        if (this.$store.state.session.ivrMap && this.$store.state.session.ivrMap[this.pbx]) {
          return this.$store.state.session.ivrMap[this.pbx].data.ivr_node_queue
        } else {
          return []
        }
      },
      pbx () {
        return this.$store.state.config.callCenter.currentPBX
      }
    },
    methods: {
      checkData () {
        let flag = false
        let peerIdFlag = false
        for (let i = 0; i < this.list.length; i++) {
          if (this.list[i].isChecked) {
            flag = true
            if (this.list[i].type === 'queue') {
              if (this.list[i].peerId === '') {
                peerIdFlag = true
                break
              }
            } else if (this.list[i].type === 'agent') {
              if (this.list[i].agent === '') {
                peerIdFlag = true
                break
              }
            }
          }
        }
        if (!flag) {
          this.$message.error('当前无选中服务号，请确认选择后重新保存!')
          return false
        }
        if (peerIdFlag) {
          this.$message.error('所选择流程内容为空，请确认选择后重新保存!')
          return false
        }
        return true
      },
      saveBatchAddService () {
        if (!this.checkData()) {
          return false
        }
        let checkoutNum = 0
        let _index = 0
        let _idArray = []
        for (let i = 0; i < this.list.length; i++) {
          if (this.list[i].isChecked) {
            checkoutNum++
            let data = {
              Type: this.form.type,
              DisplayName: '',
              PBX: this.pbx,
              Account: this.$store.state.session.account.account,
              Exten: this.list[i]._id
            }
            if (this.form.type === 'lightweight') {
              if (this.list[i].type === 'queue') {
                data.ToPeerType = 'ivr_node_queue'
                data.ToPeer = this.list[i].peerId
              } else if (this.list[i].type === 'agent') {
                data.ToPeerType = 'account_user'
                data.ToPeer = this.list[i].agent
              }
              data.ivrProcessId = ''
              this.$store.dispatch('saveLightServiceNo', data).then((res) => {
                _index = _index + 1
                if (!res.success) {
                  this.$message.error('批量保存服务号失败，为避免重复添加请重新登录系统进行保存！')
                } else if (res.success) {
                  _idArray.push(this.list[i]._id)
                }
                if (_index === checkoutNum) {
                  this.$emit('refreshService', _idArray)
                }
              })
            } else if (this.form.type === 'normal') {
              this.$store.dispatch('saveServiceNo', data).then((res) => {
                if (res.success) {
                  let saveProcess = res.serviceNoSchedule
                  delete saveProcess.Exten
                  delete saveProcess.FlowId
                  delete saveProcess.IsDefault
                  delete saveProcess.MatchedPeer
                  delete saveProcess.UnmatchedPeer
                  delete saveProcess.UpdateTime
                  delete saveProcess.UpdateUser
                  delete saveProcess.ServiceNoID
                  delete saveProcess.Times
                  saveProcess.IvrProcessId = ''
                  if (this.list[i].type === 'queue') {
                    saveProcess.ToPeerType = 'ivr_node_queue'
                    saveProcess.ToPeer = this.list[i].peerId
                  } else if (this.list[i].type === 'agent') {
                    saveProcess.ToPeerType = 'account_user'
                    saveProcess.ToPeer = this.list[i].agent
                  }
                  this.$store.dispatch('updateSchedule1', saveProcess).then((res) => {
                    _index = _index + 1
                    if (!res.success) {
                      this.$message.error('批量添加服务号流程中失败，为避免重复添加请重新登录系统进行操作')
                    } else if (res.success) {
                      _idArray.push(this.list[i]._id)
                    }
                    if (_index === checkoutNum) {
                      this.$emit('refreshService', _idArray)
                    }
                  })
                } else {
                  this.$message.error('批量保存服务号失败，为避免重复添加请重新登录系统进行保存!')
                }
              })
            }
          }
        }
      },
      getAvaliableService () {
        // if (this.$store.state.session.ivrMap && this.$store.state.session.ivrMap[this.pbx]) {
        //   let _service = this.$store.state.session.ivrMap[this.pbx].data.ivr_available_service_no
        //   let _array = []
        //   for (let i = 0; i < _service.length; i++) {
        //     let _obj = {
        //       _id: _service[i]._id,
        //       isChecked: false,
        //       type: 'queue',
        //       peerId: '',
        //       agent: ''
        //     }
        //     _array.push(_obj)
        //   }
        //   this.list = _array
        // } else {
        //   this.list = []
        // }
        if (this.availableService) {
          let _service = this.availableService
          let _array = []
          for (let i = 0; i < _service.length; i++) {
            let _obj = {
              _id: _service[i],
              isChecked: false,
              type: 'queue',
              peerId: '',
              agent: ''
            }
            _array.push(_obj)
          }
          this.list = _array
        } else {
          this.list = []
        }
      },
      powerAgent (agents) {
        let that = this
        return (agents || []).filter((item) => {
          return that.pbx === item.pbx && item.status === 'enable'
        })
      },
      saveClick () {
        this.saveBatchAddService()
      },
      cancelClick () {
        this.$emit('cancelClick')
      }
    },
    mounted () {
      this.getAvaliableService()
    }
  }
</script>

<style lang="stylus" scoped>
  @import "../../../../../assets/common.styl"
  .batch-add-service
    position relative
    height 100%
    .batch-add-service__box
      padding 20px
      box-sizing border-box
      height 100%
      overflow-y auto
  .margin-t-15
    margin-top 15px
  .margin-t-7
    margin-top 7px
  .batch-add-service__footer
    position absolute
    bottom 0
    width 100%
    background rgba(255,255,255,1)
    box-shadow 0px -2px 4px 0px rgba(5,49,38,0.05)
    border-top 1px solid rgba(232,232,232,1)
    display flex
    justify-content center
    padding 10px 0 10px
    box-sizing border-box
    .batch-add-service__button
      padding 8px 20px 8px
      box-sizing border-box
</style>
